'''
Author: your name
Date: 2020-10-30 09:50:56
LastEditTime: 2020-10-30 10:07:37
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: \python-study\博客学习\深入\装饰器.py
'''
# 装饰器(decorator)是一种高级Python语法。装饰器可以对一个函数、方法或者类进行加工。在Python中，我们有多种方法对函数和类进行加工，
# 比如在Python闭包中，我们见到函数对象作为某一个函数的返回结果。相对于其它方式，装饰器语法简单，代码可读性高。因此，装饰器在Python项目中有广泛的应用。
# 装饰器
# def decorator(F):
#     def new_F(a, b):
#         print("input", a, b)
#         return F(a, b)
#     return new_F
# 含参装饰器
def pre_str(pre=''):
    # old decorator
    def decorator(F):
        def new_F(a, b):
            print(pre + "input", a, b)
            return F(a, b)
        return new_F
    return decorator

# get square sum
@pre_str('^_^')
def square_sum(a, b):
    return a**2 + b**2

# get square diff
@pre_str('T_T')
def square_diff(a, b):
    return a**2 - b**2

# 类装饰器
def decorator(aClass):
    class newClass:
        def __init__(self, age):
            self.total_display   = 0
            self.wrapped         = aClass(age)
        def display(self):
            self.total_display += 1
            print("total display", self.total_display)
            self.wrapped.display()
    return newClass

@decorator
class Bird:
    def __init__(self, age):
        self.age = age
    def display(self):
        print("My age is",self.age)

if __name__=="__main__":
    # print(square_diff(3,4))
    # print(square_sum(3,4))
    eagleLord = Bird(5)
    for i in range(3):
        eagleLord.display()
